package com.chagee.store.operation.server.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chagee.base.exception.BaseException;
import com.chagee.base.utils.*;
import com.chagee.scm.api.supplier.response.SupplierUserBO;
import com.chagee.scm.api.supplier.service.ISupplierUserApi;
import com.chagee.store.operation.api.request.OrderAppealRequest;
import com.chagee.store.operation.common.constant.SupplierWorkOrderConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.common.utils.CommonUtil;
import com.chagee.store.operation.server.facade.SupplierWorkOrderFacade;
import com.chagee.store.operation.server.model.param.*;
import com.chagee.store.operation.server.model.response.SupplierTaskDetailResponse;
import com.chagee.store.operation.server.model.vo.*;
import com.chagee.store.operation.server.model.vo.mapVO.DictMapVo;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName SupplierWorkOrderController  //类名称
 * @Description: //类描述:供应商小程序端接口
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/04/25 11:19	//创建时间
 * @UpdateUser: Jacky-zhan	//作者
 * @UpdateDate: 2024/04/25 11:19	//更新时间
 * @UpdateRemark: 更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/app/supplier/workOrder")
public class SupplierWorkOrderController {

	@Resource
	private SupplierWorkOrderFacade supplierWorkOrderFacade;

	@Resource
	private ISupplierUserApi iSupplierUserApi;

	@Value("${loginUser.roleName:城市骨干,机动队}")
	private String roleName;

	//获取当前的登录人信息的后端方法
	public SupplierUserBO getUser() {
		BladeUser user = AuthUtil.getUser();
		if (Objects.isNull(user)) {
			throw new BizException(BizErrorCode.NOT_GTE_LOGIN_USER_INFO);
		}
		SoaResponse<SupplierUserBO, BaseException> supplierUserBO = iSupplierUserApi.queryByUserId(String.valueOf(user.getUserId()));
		if (Objects.isNull(supplierUserBO.getResponseVo())) {
			throw new BizException(BizErrorCode.NOT_GTE_LOGIN_USER_JOIN_SUPPLIER_INFO);
		}
		log.info("login_getUser{}", JSONObject.toJSONString(supplierUserBO.getResponseVo()));
		return supplierUserBO.getResponseVo();
	}

	@PostMapping("/list")
	@ApiOperation("供应商获取工单列表查询")
	public HttpResponse<PaginationData<SupplierWorkOrderVO>> list(@RequestBody @Valid PaginationRequest<SupplierWorkOrderQueryParam> queryParam) {
		log.info("#SupplierWorkOrderController.list#request{}, auth:{}", queryParam, JSON.toJSONString(AuthUtil.getUser()));
		SupplierWorkOrderQueryParam param = queryParam.getQueryParameter();
		//获取登录信息
		SupplierUserBO supplierUserBO = getUser();
		param.setReceiverID(Long.valueOf(supplierUserBO.getUserId()));
		//账号类型 1-主账号 2-子账号（类型不同查询范围不一样）
		param.setUserType(supplierUserBO.getUserType());
		param.setSupplierId(supplierUserBO.getSupplierBaseId());
		param.setSupplierNo(supplierUserBO.getSupplierBaseCode());
		PaginationData<SupplierWorkOrderVO> result = new PaginationData<>();
		// 城市骨干角色 当前登录人所属供应商下的工单
		List<String> roleList = Arrays.stream(roleName.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
		if (roleList.contains(supplierUserBO.getRoleName())) {
			result = supplierWorkOrderFacade.queryWorkOrderList(queryParam);
		} else {
			result = supplierWorkOrderFacade.list(queryParam);
		}
		return HttpResponseUtil.success(result);
	}

	@PostMapping("/scanCodePlaceOrder")
	@ApiOperation("供应商到门店扫码下单")
	public HttpResponse<ScanResponse> scanCodeAndPlaceOrder(@RequestBody @Valid ScanCodePlaceOrderParam scanCodePlaceOrderParam) {
		log.info("#SupplierWorkOrderController.scanCodeAndPlaceOrder{}", JSONObject.toJSONString(scanCodePlaceOrderParam));
		//获取登录信息
		SupplierUserBO supplierUserBO = getUser();
		scanCodePlaceOrderParam.setReceiverID(Long.valueOf(supplierUserBO.getUserId()));
		scanCodePlaceOrderParam.setReceiver(supplierUserBO.getName());
		scanCodePlaceOrderParam.setReceiverMobile(supplierUserBO.getMobile());
		scanCodePlaceOrderParam.setSupplier(supplierUserBO.getSupplierName());
		//账号类型 1-主账号 2-子账号（类型不同查询范围不一样）
		scanCodePlaceOrderParam.setUserType(supplierUserBO.getUserType());
		scanCodePlaceOrderParam.setSupplierId(supplierUserBO.getSupplierBaseId());
		scanCodePlaceOrderParam.setSupplierNo(supplierUserBO.getSupplierBaseCode());
		ScanResponse result = supplierWorkOrderFacade.scanCodeAndPlaceOrder(scanCodePlaceOrderParam);
		return HttpResponseUtil.success(result);
	}

	@PostMapping("/getCompanyList")
	@ApiOperation("供应商获取子公司列表")
	public HttpResponse<List<CompanyVO>> getCompanyList(@RequestBody @Valid GetCompanyStoreParam getCompanyStoreParam) {
		log.info("#SupplierWorkOrderController.getCompanyList#request{}", getCompanyStoreParam);
		//获取登录信息
		SupplierUserBO supplierUserBO = getUser();
		//账号类型 1-主账号 2-子账号（类型不同查询范围不一样）
		getCompanyStoreParam.setUserType(supplierUserBO.getUserType());
		if (SupplierWorkOrderConstant.USER_TYPE_MAIN_ACCOUNT.equals(String.valueOf(getCompanyStoreParam.getUserType()))) {
			getCompanyStoreParam.setSupplierId(supplierUserBO.getSupplierBaseId());
		}
		if (SupplierWorkOrderConstant.USER_TYPE_SUB_ACCOUNTS.equals(String.valueOf(getCompanyStoreParam.getUserType()))) {
			getCompanyStoreParam.setReceiverID(Long.valueOf(supplierUserBO.getUserId()));
		}
		getCompanyStoreParam.setReceiver(supplierUserBO.getName());
		List<CompanyVO> result = supplierWorkOrderFacade.getCompanyList(getCompanyStoreParam);
		return HttpResponseUtil.success(result);
	}

	@PostMapping("/getCompanyStoreList")
	@ApiOperation("供应商获取子公司-门店列表")
	public HttpResponse<PaginationData<CompanyStorePageVO>> getCompanyStoreList(@RequestBody @Valid PaginationRequest<GetCompanyStoreParam> getCompanyStoreParamPaginationRequest) {
		log.info("#SupplierWorkOrderController.getCompanyStoreList#request{}", getCompanyStoreParamPaginationRequest);
		GetCompanyStoreParam queryParameter = getCompanyStoreParamPaginationRequest.getQueryParameter();
		//获取登录信息
		SupplierUserBO supplierUserBO = getUser();
		//账号类型 1-主账号 2-子账号（类型不同查询范围不一样）
		queryParameter.setUserType(supplierUserBO.getUserType());
		if (SupplierWorkOrderConstant.USER_TYPE_MAIN_ACCOUNT.equals(String.valueOf(queryParameter.getUserType()))) {
			queryParameter.setSupplierId(supplierUserBO.getSupplierBaseId());
		}
		if (SupplierWorkOrderConstant.USER_TYPE_SUB_ACCOUNTS.equals(String.valueOf(queryParameter.getUserType()))) {
			queryParameter.setReceiverID(Long.valueOf(supplierUserBO.getUserId()));
		}
		queryParameter.setReceiver(supplierUserBO.getName());
		PaginationData<CompanyStorePageVO> pageVOPaginationData = supplierWorkOrderFacade.getCompanyStoreList(getCompanyStoreParamPaginationRequest);
		return HttpResponseUtil.success(pageVOPaginationData);
	}

	@PostMapping("/getCompanyByStore")
	@ApiOperation("供应商通过门店编码获取子公司信息")
	public HttpResponse<CompanyStoreVO> getCompanyByStore(@RequestBody @Valid ReQueryCompanyParam reQueryCompanyParam) {
		log.info("#SupplierWorkOrderController.getCompanyByStore#request{}", reQueryCompanyParam);
		CompanyStoreVO companyStoreVO = supplierWorkOrderFacade.getCompanyByStore(reQueryCompanyParam);
		return HttpResponseUtil.success(companyStoreVO);
	}

	@PostMapping("/getWorkOrderInfo")
	@ApiOperation("供应商获取工单详情")
	public HttpResponse<SupplierWorkOrderTaskVO> getWorkOrderInfo(@RequestBody @Valid SupplierWorkOrderTaskParam supplierWorkOrderTaskParam) {
		log.info("#SupplierWorkOrderController.getWorkOrderInfo#request{}, auth:{}", JSON.toJSONString(supplierWorkOrderTaskParam), JSON.toJSONString(AuthUtil.getUser()));
		SupplierWorkOrderTaskVO result = supplierWorkOrderFacade.queryData(supplierWorkOrderTaskParam);
		return HttpResponseUtil.success(result);
	}

	@PostMapping("/dealWorkOrder")
	@ApiOperation("供应商完成打烊任务")
	public HttpResponse<SupplierWorkOrderTaskVO> dealWorkOrder(@RequestBody @Valid SupplierDealWorkOrderParam supplierDealWorkOrderParam) {
		log.info("#SupplierWorkOrderController.dealWorkOrder#request{}", supplierDealWorkOrderParam);
		SupplierWorkOrderTaskVO result = supplierWorkOrderFacade.dealWorkOrder(supplierDealWorkOrderParam);
		return HttpResponseUtil.success(result);
	}

	@PostMapping("/confirmHandoverData")
	@ApiOperation("供应商确认预打烊完成情况交接项")
	public HttpResponse<Boolean> confirmHandoverData(@RequestBody @Valid SupplierDeviceConfirmHandoverParam supplierDeviceConfirmHandoverParam) {
		log.info("#SupplierWorkOrderController.confirmHandoverData#request{}", supplierDeviceConfirmHandoverParam);
		Boolean result = supplierWorkOrderFacade.confirmHandoverData(supplierDeviceConfirmHandoverParam);
		return HttpResponseUtil.success(result);
	}


	@PostMapping("/submitAppeal")
	@ApiOperation("供应商对工单任务验收结果不合格的提起申诉")
	public HttpResponse<Boolean> submitAppeal(@RequestBody @Valid SubmitAppealRequest submitAppealRequest) {
		log.info("#SupplierWorkOrderController.submitAppeal#request{}", JSON.toJSONString(submitAppealRequest));
		Boolean result = supplierWorkOrderFacade.submitAppeal(submitAppealRequest);
		return HttpResponseUtil.success(result);
	}

	@GetMapping("/dict")
	@ApiOperation("门店数据字典")
	public HttpResponse<DictMapVo> dict() {
		return HttpResponseUtil.success(supplierWorkOrderFacade.dictionary());
	}

	@PostMapping("/dealTask")
	@ApiOperation("供应商对任务去处理/修改")
	public HttpResponse<TaskExecutionDetailResponse> dealTask(@RequestBody @Valid SupplierDealTaskRequest supplierDealTaskRequest) {
		log.info("#SupplierWorkOrderController.dealTask#request{}", JSONObject.toJSONString(supplierDealTaskRequest));
		//获取登录信息
		SupplierUserBO supplierUserBO = getUser();
		supplierDealTaskRequest.setSubmitter(supplierUserBO.getName());
		supplierDealTaskRequest.setSubmitterMobile(supplierUserBO.getMobile());
		TaskExecutionDetailResponse result = supplierWorkOrderFacade.dealTask(supplierDealTaskRequest);
		return HttpResponseUtil.success(result);
	}

	@PostMapping("/getTaskInfo")
	@ApiOperation("供应商获取任务详情")
	public HttpResponse<SupplierTaskDetailResponse> getTaskInfo(@RequestBody @Valid SupplierTaskExecutionParam param) {
		log.info("#SupplierWorkOrderController.getTaskInfo#request{}", JSONObject.toJSONString(param));
		SupplierTaskDetailResponse result = supplierWorkOrderFacade.getTaskInfo(param);
		return HttpResponseUtil.success(result);
	}

	@PostMapping("/orderAppeal")
	@ApiOperation("过期工单发起申诉")
	public HttpResponse<Boolean> orderAppeal(@RequestBody @Valid OrderAppealRequest request) {
		log.info("#SupplierWorkOrderController.orderAppeal#request{}, auth:{}", JSON.toJSONString(request), JSON.toJSONString(AuthUtil.getUser()));
		if (StringUtils.isNotBlank(CommonUtil.validate(request))) {
			return HttpResponseUtil.build(null, BizErrorCode.REQUEST_VALID_FAILED.getErrorCode(), CommonUtil.validate(request));
		}
		return HttpResponseUtil.success(supplierWorkOrderFacade.orderAppeal(request));
	}

}
